#include <stdio.h>
#include <string.h>
#include <limits.h>

char out[1000];
void reverse(char s[]);
void itoa(int n, char s[]);

int main()
{
    int n = INT_MIN;
    printf("n = %d, -n = %d\n", n, -1 * n);
    
    itoa(n, out);
    printf("out = %s\n", out);
    return 0;
}

void reverse(char s[])
{
    int c, i, j;
    for (i = 0, j = strlen(s) - 1; i < j; i++, j--)
    {
        c = s[i];
        s[i] = s[j];
        s[j] = c;
    }
}

/* 
 * 原有的itoa函数不能处理最大的负数是因为最大的负数乘以-1之后超出了最大正数的范围。
*/

void itoa(int n, char s[])
{
    int i, sign;
    unsigned int t;

    if((sign = n) < 0)
        t = -n;
    else
    {
        t = n;
    }
    
    i = 0;
    do{
        s[i++] = t % 10 + '0';
    } while ((t /= 10) > 0);

    if(sign < 0)
        s[i++] = '-';
    
    s[i] = '\0';
    reverse(s);
}